package 二叉树;

import com.sun.source.tree.Tree;

public class LC_450删除二叉搜索树中的节点 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public TreeNode deleteNode(TreeNode root, int key) {
        //未找到目标值
        if(root==null)
            return null;
        //找到目标值
        if(root.val==key){
            //叶子结点
            if(root.left==null&&root.right==null)
                return null;
            //左不空右空
            else if(root.left!=null&&root.right==null)
                return root.left;
            //右空左不空
            else if(root.left==null&&root.right!=null)
                return root.right;
            //左右都不空
            else {
                TreeNode cur=root.right;
                while(cur.left!=null)
                    cur=cur.left;
                cur.left=root.left;
                return root.right;
            }
        }
        if(key<root.val)
            root.left=deleteNode(root.left,key);
        if(key>root.val)
            root.right=deleteNode(root.right,key);
        return root;
    }
}
